package com.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

@SuppressWarnings("unchecked")
public class EncodingFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String method = request.getMethod();

		if (method.equals("POST")) {
			/**
			 * setCharacterEncoding方法只针对POST请求有效。
			 */
			req.setCharacterEncoding("UTF-8");
		} else {
			req = new GetRequestObj(request);
		}

		res.setCharacterEncoding("UTF-8");
		chain.doFilter(req, res);

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

	class GetRequestObj extends HttpServletRequestWrapper {

		public GetRequestObj(HttpServletRequest request) {
			super(request);
		}


		/**
		 * 使用EL表达式{param.参数名称}，调用是该方法，
		 */
		public String getParameter(String name) {
			String param_value = super.getParameter(name);
			if (param_value != null && !param_value.equals("")) {
				try {
					param_value = new String(
							param_value.getBytes("ISO-8859-1"), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			return param_value;
		}

		/**
		 * 使用OGNL表达式#parameter.参数名称，调用的是该方法。
		 */

		@SuppressWarnings("rawtypes")
		public Map getParameterMap() {
			Map paramMap = super.getParameterMap();
			Map returnMap = new HashMap();
			// System.out.println("getParameterMap" + paramMap);
			Set<String> keySet = paramMap.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				/**
				 * 不能直接改动valueArray里面的值。
				 * 
				 * 如果产生多次调用，在第一次转为UTF-8编码，后面再调时，
				 * 
				 * 正常的编码就会转为乱码。
				 * 
				 * 因此，重新产生一个新的数组，不改动原先的数组中的值。
				 * 
				 */
				String[] valueArray = (String[]) paramMap.get(key);
				String newvalues[] = new String[valueArray.length];
				for (int i = 0; i < valueArray.length; i++) {
					String value = valueArray[i];
					try {
						value = new String(value.getBytes("iso8859-1"), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					newvalues[i] = value; // 解决乱码后封装到Map中
				}

				returnMap.put(key, newvalues);

			}
			return returnMap;
		}
	}

	public static void main(String[] args) {
		String str = "中文";

		try {
			System.out.println(URLEncoder.encode(str, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
